from flask import Blueprint, request, jsonify, g
from flask_restful import Api, Resource, reqparse

from models.models import *
from utils.jwt_tool import gen_toen,check_token

order_bp = Blueprint("order",__name__)


api = Api(order_bp)




#订单增删改查
class OrderView(Resource):
    def post(self):

        req = reqparse.RequestParser()
        req.add_argument("token")

        req.add_argument("c_id",help="大纲id错误")
        args = req.parse_args()
        print("获取的大纲的id",args['c_id'])
        payload = check_token(args['token'])
        sid = payload.get('sid')
        #查询大纲的单条信息
        cour_info = Course.query.filter(Course.id == args['c_id']).first()
        print("<<<",cour_info)
        money1 = cour_info.money  #大纲的价格

        #查询用户的信息  余额
        stu_info = Stu.query.filter(Stu.id == sid).first()
        money2 = stu_info.money  #用户余额

        if money2 < money1:
            return jsonify({
                "code":400,
                "msg":"请充QQ币"
            })
        money3 = money2-money1
        #特色课数量
        course_num1 = stu_info.course_num
        course_num1 += 1

        #修改用户QQ币余额和特色课的数量
        Stu.query.filter(Stu.id == sid).update({
            "money":money3,
            "course_num":course_num1
        })
        db.session.commit()
        #查看是否有该订单
        couorde_info = CourseOrder.query.filter(CourseOrder.c_id == args['c_id'],CourseOrder.s_id == s_id).first()
        if  couorde_info:
            return jsonify({
                "code":200,
                "msg":"您有改订单，无法订购"
            })
        #创建订单
        try:
            couord = CourseOrder(c_id=args['c_id'], s_id=sid)
            db.session.add(couord)
            db.session.commit()
            print("订单添加成功")
            return jsonify({
                "code":200,
                "msg":"订单创建成功"
            })
        except Exception  as e:
            print("订单创建失败",e)
            return jsonify({
                "code":400,
                "msg":"课程创建失败"
            })

api.add_resource(OrderView,"/cou_order_url")








